package com.dayaokeji.rhythmschoolstudent.client.mine.account;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.utils.InputUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.SmsApi;
import com.dayaokeji.server_api.domain.SendSmsType;
import com.dayaokeji.server_api.domain.Sms;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 验证手机号码
 */
public class VerifyPhoneNumberActivity extends BaseActivity {

    public static final String EXTRA_VERIFY_TYPE = "verify_type";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.et_verify_code)
    EditText etVerifyCode;
    @BindView(R.id.btn_send_verify_code)
    Button btnSendVerifyCode;

    private String mobile;
    private int verifyType;
    private ProgressDialog checkProgressDialog;

    private final SmsApi smsApi = ApiUtils.getApi(SmsApi.class);
    private Call<ServerResponse<Void>> sendSmsCall;
    private Call<ServerResponse<Boolean>> validateSmsCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        setSupportActionBar(toolbar);

        verifyType = getIntent().getIntExtra(EXTRA_VERIFY_TYPE, -1);
        if (verifyType == -1) {
            ToastUtils.warning(R.string.data_incorrect);
            return;
        }
    }

    @OnClick({
            R.id.btn_next,
            R.id.btn_send_verify_code
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_next:
                checkVerifyCode();
                break;
            case R.id.btn_send_verify_code:
                sendVerifyCode();
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void sendVerifyCode() {
        if (InputUtils.validateInput(etMobile,"请输入手机号码")) {
            mobile = etMobile.getText().toString().replace(" ", "").trim();
            if (mobile.length() == 11 && TextUtils.isDigitsOnly(mobile)) {
                final Sms sendSms = new Sms();
                sendSms.setPhone(mobile);
                if (Constant.MOBILE_VERIFY_TYPE_REGISTER == verifyType) {
                    sendSms.setType(SendSmsType.REGISTER.getType());
                }
                if (Constant.MOBILE_VERIFY_TYPE_FORGET_PASSWORD == verifyType) {
                    sendSms.setType(SendSmsType.FORGET_PASSWORD.getType());
                }
                sendSmsCall = smsApi.send(sendSms);
                sendSmsCall.enqueue(new ServerCallback<Void>(this,"正在发送短信验证码...") {
                    @Override
                    public void onResponse(boolean success, ServerResponse<Void> response) {
                        if (success) {
                            if (countDownTimer != null) {
                                countDownTimer.start();
                            }
                            ToastUtils.success("发送验证码成功");
                        }else{
                            ToastUtils.warning("发送验证码失败");
                            if (countDownTimer != null) {
                                countDownTimer.onFinish();
                            }
                        }
                    }
                });
            }else{
                ToastUtils.warning("请输入11位手机号码");
            }

        }
    }

    /**
     * 验证验证码
     */
    private void checkVerifyCode() {
        if (InputUtils.validateInput(etMobile,"请输入手机号码") && InputUtils.validateInput(etVerifyCode,"请输入验证码")) {
            String verifyCode = etVerifyCode.getText().toString().trim();
            final Sms sms = new Sms();
            sms.setPhone(mobile);
            if (Constant.MOBILE_VERIFY_TYPE_REGISTER == verifyType) {
                sms.setType(SendSmsType.REGISTER.getType());
            }
            if (Constant.MOBILE_VERIFY_TYPE_FORGET_PASSWORD == verifyType) {
                sms.setType(SendSmsType.FORGET_PASSWORD.getType());
            }
            sms.setCode(verifyCode);
            validateSmsCall = smsApi.validate(sms);
            validateSmsCall.enqueue(new ServerCallback<Boolean>(this,"正在验证...") {
                @Override
                public void onResponse(boolean success, ServerResponse<Boolean> response) {
                    if (success) {
                        if (response.getBody() != null && response.getBody().booleanValue()) {
                            next();
                        }else{
                            ToastUtils.warning("验证码失效");
                            if (countDownTimer != null) {
                                countDownTimer.onFinish();
                            }
                        }
                    }
                }
            });
        }
    }

    private void next() {
        if (Constant.MOBILE_VERIFY_TYPE_REGISTER == verifyType) {
            toRegister();
        }else if (Constant.MOBILE_VERIFY_TYPE_FORGET_PASSWORD == verifyType) {
            toForgetPassword();
        }
        ActivityStackManager.finish();
    }

    /**
     * 注册
     */
    private void toRegister() {
        Intent intent = new Intent(this, RegisterNextActivity.class);
        intent.putExtra(RegisterNextActivity.EXTRA_MOBILE_NUMBER,mobile);
        startActivity(intent);
    }

    /**
     * 忘记密码
     */
    private void toForgetPassword() {
        Intent intent = new Intent(this, ForgetPasswordActivity.class);
        intent.putExtra(ForgetPasswordActivity.EXTRA_MOBILE_NUMBER,mobile);
        startActivity(intent);
    }

    private CountDownTimer countDownTimer = new CountDownTimer(60 * 1000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (btnSendVerifyCode != null) {
                btnSendVerifyCode.setEnabled(false);
                btnSendVerifyCode.setText("已发送（ " + millisUntilFinished / 1000 + " s）");
            }
        }

        @Override
        public void onFinish() {
            if (btnSendVerifyCode != null) {
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                btnSendVerifyCode.setText("重新获取验证码");
                btnSendVerifyCode.setEnabled(true);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (sendSmsCall != null) {
            sendSmsCall.cancel();
        }
        if (validateSmsCall != null) {
            validateSmsCall.cancel();
        }
    }
}
